package player

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/advert"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/sp"

	log "github.com/sirupsen/logrus"
)

// 获取占卜事件结果 60001
func (p *Player) ScryerReqRequest(req *sp.ScryerReqRequest) (res *sp.ScryerReqResponse) {
	us := p.User
	//成就，记录占卜次数。
	lib.AddAchievProgress(us, data.AchievementType.Pick_Crystalball, 1)
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(us)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	scryerInfo := us.GetScryerInfoData()
	// State状态 0-没有记录 1-有记录
	// CanReTry重试 0-可以重试 1-不可重试
	if scryerInfo.State == 1 && scryerInfo.CanReTry == 1 {
		//有记录，并且不可重试
		err := errors.NewErrcode(data.Errcode.ConfigNotFound, "占卜不能再次获取")
		log.WithFields(log.Fields{
			"uid":    p.User.Uid.Hex(),
			"state":  scryerInfo.State,
			"method": "ScryerReqRequest",
		}).Debug("占卜不能再次获取")
		res = &sp.ScryerReqResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	eventId, err := lib.GetRandomScryerEvent(us, p.Send)
	if err != nil {
		res = &sp.ScryerReqResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	//eventId = (eventId + 1)    // 数组索引自增1，变为事件id
	if scryerInfo.State == 0 { // 没有记录，当前为第一次摇，设置为可以重试
		scryerInfo.State = 1
		scryerInfo.CanReTry = 0
	} else { // state == 1 可以重试，也标识已经摇过一次了，有记录了
		scryerInfo.State = 1 // 有记录，设置为不可重试
		scryerInfo.CanReTry = 1
		advert.Module.AddAdCnt(data.AdMagicBall)                         // 统计占卜广告
		advert.Module.AddAdUser(us.Uid.Hex(), us.Name, data.AdMagicBall) // 统计占卜广告
	}
	scryerInfo.Id = eventId        // 记录事件id
	scryerInfo.GridId = req.GridId // 记录水晶球位置
	scryerInfo.Update(scryerInfo)

	res = &sp.ScryerReqResponse{
		Id:       eventId,
		CanReTry: scryerInfo.CanReTry,
		State:    scryerInfo.State,
	}
	return
}

// 占卜事件 接受结果 60002
func (p *Player) ScryerAcceptRequest(req *sp.ScryerAcceptRequest) (res *sp.ScryerAcceptResponse) {
	acceptId := req.Id // 事件id
	// 获得道具函数
	Givefunc := func(eventId int64) (r *sp.ScryerAcceptResponse) {
		uProp, resGoodsList, boxResList, err := lib.GiveScryerAcceptRewards("ScryerAcceptRequest", p.User, eventId, p.Send)
		if err != nil {
			r = &sp.ScryerAcceptResponse{
				Errcode: errors.ErrCode(err),
			}
			return
		}
		// 有成就完成，进行通知
		achLst := lib.AchievComplete(p.User)
		if len(achLst) > 0 {
			p.Send(&sp.AchievementNoticeRequest{
				Lst: achLst,
			})
		}
		r = &sp.ScryerAcceptResponse{
			Id:     acceptId,
			Res:    lib.FormatGoodsInfoSps(resGoodsList),
			BoxRes: lib.FormatBoxResSps(boxResList),
		}
		if uProp != nil {
			p.TimelyUpdateProp(req.GetType(), uProp)
			utils.AsyncFunc(func() {
				p.UpdateProp(req.GetType(), uProp)
			})
		}
		return
	}
	// 失去道具函数
	LoseFunc := func(eventId int64) (r *sp.ScryerAcceptResponse) {
		uProp, resGoodsList, err := lib.LoseScryerAcceptRewards(p.User, eventId)
		if err != nil {
			r = &sp.ScryerAcceptResponse{
				Errcode: errors.ErrCode(err),
			}
			return
		}
		r = &sp.ScryerAcceptResponse{
			Id:  acceptId,
			Res: lib.FormatGoodsInfoSps(resGoodsList),
		}
		p.TimelyUpdateProp(req.GetType(), uProp)
		utils.AsyncFunc(func() {
			p.UpdateProp(req.GetType(), uProp)
		})
		return
	}
	// 获得Buff函数
	GiveBuffFunc := func(eventId int64, scryData *m.ScryerInfoData) (r *sp.ScryerAcceptResponse) {
		err := lib.GiveScryBuffRewards(p.User, eventId, scryData)
		if err != nil {
			//获得Buff失败
		}
		r = &sp.ScryerAcceptResponse{
			Id: acceptId,
		}
		return
	}

	//根据事件id分发处理事件
	scryerInfo := p.User.GetScryerInfoData()
	// 重试 0-可以重试 1-不可重试
	// 状态 0-没有记录 1-有记录
	if scryerInfo.State == 0 {
		log.WithFields(log.Fields{
			"uid":      p.User.Uid.Hex(),
			"state":    scryerInfo.State,
			"canReTry": scryerInfo.CanReTry,
			"gridid":   scryerInfo.GridId,
			"eventId":  "1",
			"method":   "ScryerAcceptRequest",
		}).Debug("没有上次的占卜记录，不能发送奖励")
		err := errors.NewErrcode(data.Errcode.ConfigNotFound, "没有上次的占卜记录，不能发送奖励")
		res = &sp.ScryerAcceptResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	// 读表
	tpl, ok := data.Get("ScryerRewards", uint64(acceptId))
	if !ok {
		err := errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到占卜事件配置,ScryerRewards")
		log.WithFields(log.Fields{
			"method":   "ScryerAcceptRequest",
			"acceptId": acceptId,
		}).Error("ScryerAcceptRequest.读表ScryerRewards失败，找不到ID")
		res = &sp.ScryerAcceptResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	// 更新当前层 格子信息
	gridInfo, _ := p.User.GetGrid(scryerInfo.GridId)
	gridInfo.Goods = nil
	p.User.GetLayer().UpdateGrid(gridInfo)

	configInfo := tpl.(data.ScryerReward)
	//分发事件
	switch configInfo.Typ {
	//天灾：水晶球位置9宫格陨石焦土
	case "Interactive":
		if configInfo.Id == 1 {
			layer, err := lib.ScryerFire(p.User, req.GridIds)
			if err != nil {
				res = &sp.ScryerAcceptResponse{
					Errcode: errors.ErrCode(err),
					Id:      acceptId,
				}
			} else {
				res = &sp.ScryerAcceptResponse{
					Id:    acceptId,
					Layer: lib.FormartLayerSp(layer),
				}
			}
		}
	case "Buff":
		//2:Buff财势：5个格子半价
		//3:幸运：十分钟挖宝金币增加200%
		res = GiveBuffFunc(int64(configInfo.Id), scryerInfo)
	case "GetRes":
		//4.自然：获得，宠物口粮N个
		//5.活力：获得，老虎机体力N个
		res = Givefunc(int64(configInfo.Id))
	case "LoseRes":
		//6.厄运：失去，当前关卡3级格子金币
		res = LoseFunc(int64(configInfo.Id))
	case "Ad":
		//7.交易：观看广告，获得，砖石N个
		res = Givefunc(int64(configInfo.Id))

		// 成就，记录观看广告
		lib.AddAchievProgress(p.User, data.AchievementType.Watch_ads, 1)
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	scryerInfo = p.User.GetScryerInfoData()
	scryerInfo.State = 0
	scryerInfo.CanReTry = 0
	defer scryerInfo.Update(scryerInfo)

	// 更新层级信息
	r := p.User.GetLayer().GridList
	defer func() {
		p.User.GetLayer().UpdateGridByMap(r)
	}()

	res.GInfo = lib.FormartGridInfoSp(gridInfo)
	return
}

// 主动推送占卜事件状态 s-c 60003
func (p *Player) ScryerInfoPush() {
	scryerInfo := p.User.GetScryerInfoData()
	// 重试 0-可以重试 1-不可重试
	// 状态 0-没有记录 1-有记录
	if scryerInfo.State == 0 {
		// log.WithFields(log.Fields{
		// 	"Id":     scryerInfo.Id,
		// 	"GridId": scryerInfo.GridId,
		// 	"State":  scryerInfo.State,
		// 	"method": "ScryerInfoGetRequest",
		// }).Debug("占卜断线请求")
		res := &sp.ScryerInfoGetRequest{
			Errcode:  data.Errcode.NotFound,
			BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
		}
		p.Send(res)
		return
	}

	gridinfo, ok := p.User.GetGrid(scryerInfo.GridId)
	if !ok {
		err := errors.NewErrcode(data.Errcode.NoGrid, "没有该格子")
		res := &sp.ScryerInfoGetRequest{
			Errcode:  errors.ErrCode(err),
			BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
		}
		p.Send(res)
		return
	}
	// if gridinfo.Status != 0 {
	// 	err := errors.NewErrcode(data.Errcode.GridNoOpen, "格子没有翻开")
	// 	res = &sp.ScryerInfoGetRequest{
	// 		Errcode:  errors.ErrCode(err),
	// 		BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
	// 	}
	// 	return
	// }
	if gridinfo.Goods == nil {
		err := errors.NewErrcode(data.Errcode.GridNoGoods, "没有物品")
		res := &sp.ScryerInfoGetRequest{
			Errcode:  errors.ErrCode(err),
			BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
		}
		p.Send(res)
		return
	}
	if gridinfo.Goods.Tid != 150411 {
		err := errors.NewErrcode(data.Errcode.ServerErr, "不是水晶球")
		res := &sp.ScryerInfoGetRequest{
			Errcode:  errors.ErrCode(err),
			BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
		}
		p.Send(res)
		return
	}

	res := &sp.ScryerInfoGetRequest{
		Id:       scryerInfo.Id,
		GridId:   scryerInfo.GridId,
		State:    scryerInfo.State,
		CanReTry: scryerInfo.CanReTry,
		BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
	}
	p.Send(res)
	return
}

// 放弃占卜事件 60004
func (p *Player) ScryerAbandonRequest(req *sp.ScryerAbandonRequest) (res *sp.ScryerAbandonResponse) {
	scryerInfo := p.User.GetScryerInfoData()
	// 重试 0-可以重试 1-不可重试
	// 状态 0-没有记录 1-有记录
	scryerInfo.State = 0
	scryerInfo.CanReTry = 0
	defer scryerInfo.Update(scryerInfo)

	// 更新当前层 格子信息
	gridInfo, _ := p.User.GetGrid(scryerInfo.GridId)
	gridInfo.Goods = nil
	p.User.GetLayer().UpdateGrid(gridInfo)
	// 更新层级信息
	r := p.User.GetLayer().GridList
	defer p.User.GetLayer().UpdateGridByMap(r)

	res = &sp.ScryerAbandonResponse{
		Errcode: 0,
		GInfo:   lib.FormartGridInfoSp(gridInfo),
	}
	return
}

// 获取占卜事件Buff 60005
func (p *Player) ScryGetBuffRequest(req *sp.ScryGetBuffRequest) (res *sp.ScryGetBuffResponse) {
	scryerInfo := p.User.GetScryerInfoData()
	if scryerInfo.ScryBuffList == nil {
		err := errors.NewErrcode(data.Errcode.NotFound, "占卜Buff列表为nil")
		res = &sp.ScryGetBuffResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	res = &sp.ScryGetBuffResponse{
		Errcode:  0,
		BuffList: lib.FormatScryBuffList(scryerInfo.ScryBuffList),
	}
	return
}

func (p *Player) gmAddScryBuff(buffId int64) {
	_ = lib.GiveScryBuffByBuffId(p.User, buffId)
}
